<template>
	<view class="main">
		<view v-if="canIUse">
			<view class="logo">
				<image src="../../static/image/logo.png"></image>
			</view>
			<view class="h1">申请获取以下权限</view>
			<view class="p">{{tip}}</view>

			<view class="btn-wrap">
				<button v-if="isShow" class="btn" open-type="getUserInfo" @click="getUserInfo">微信授权</button>
				<button v-else class="btn" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber"
					withCredentials="true">绑定手机号</button>
			</view>
		</view>
		<view v-else class="tips">请升级微信版本</view>
		<u-modal v-model="show" content="授权成功，为了正常使用功能，请继续绑定手机号！"></u-modal>
	</view>
</template>

<script>
	const WXBizDataCrypt = require('../../common/WXBizDataCrypt.js');
	export default {
		data() {
			return {
				canIUse: wx.canIUse('button.open-type.getUserInfo'),
				isShow: true,
				show: false,
				tip: '获得您的公开信息（昵称，头像等）',
				appid: 'wx377394a505238103',
				sessionKey: '',
				openid: '',
				bid: [],
				auditId: '', //被审核id
			}
		},
		onLoad(options) {
			if (options.auditId) {
				this.auditId = options.auditId;
			}
		},
		onShow() {
			this.bid = uni.getStorageSync('bid');
			const res = uni.getSystemInfoSync();
			uni.setStorageSync('environment', res.environment);
			if (res.environment === 'wxwork') {
				console.log('企业微信环境中');
			} else {
				console.log('微信环境中');
			}
		},
		methods: {
			getUserInfo() {
				let that = this;
				let environment = uni.getStorageSync('environment');
				if (environment === 'wxwork') {
					// 企业微信环境中
					console.log('企业微信环境中');
					wx.qy.login({
						success: function(res) {
							if (res.code) {
								//发起网络请求
								let code = res.code;
								that.$u.api.qyCode2SessionSmall({
									code: code,
									type: 4, //类型 4 人员实名制登记 
								}).then(res => {
									if (res.code == 0) {
										that.$u.api.qyLogin({
											userId: res.data.userId,
											phone: res.data.phone,
											type: 4
										}).then(res => {
											if (res.code == 0) {
												uni.setStorageSync('token', res.data.token);
												uni.setStorageSync('user', res.data.user);
												uni.setStorageSync('show', res.data.show);
												that.$u.toast('登录成功!正在跳转……');
												if (that.bid.id && that.bid.name) {
													// 扫码进入
													uni.reLaunch({
														url: './certification?id=' +
															that.bid.id + '&name=' +
															that
															.bid.name
													})
												} else if (that.auditId) {
													// 企业微信通知进入-认证审核页面
													uni.reLaunch({
														url: './certificationAuditPersonalInfo?id=' +
															that.auditId
													})
												} else {
													uni.reLaunch({
														url: './certification'
													})
												}
											}
										})
									}
								})
							} else {
								console.log('登录失败！' + res.errMsg)
								that.$u.toast('登录失败！' + res.errMsg);
							}
						}
					});
				} else {
					// 微信环境中
					console.log('微信环境中');

					wx.getUserProfile({
						lang: 'zh_CN',
						desc: "获取信息",
						success: (info) => {
							that.tip = '获得您的公开信息（手机号等）';
							that.show = true;
							uni.setStorageSync('my', info.userInfo)
							uni.login({
								provider: 'weixin',
								success: res => {
									that.isShow = false;
									let code = res.code
									that.$u.api.userCode2Session({
										code: code,
										type: 0, //类型 0 人员实名制登记  1 人员安全学习平台
									}).then(res => {
										if (res.code == 0) {
											that.openid = res.data.openid;
											that.sessionKey = res.data.session_key;
										}
									})
								},
								fail: () => {},
								complete: () => {}
							});
						},
						fail: (err) => {
							console.log('授权失败~')
						}
					})
				}
			},
			getPhoneNumber(e) {
				let that = this;
				if (e.detail.errMsg == "getPhoneNumber:ok") {
					// 手机号解密-前端
					const pc = new WXBizDataCrypt(that.appid, that.sessionKey)
					const data = pc.decryptData(e.detail.encryptedData, e.detail.iv)

					that.$u.api.userLogin({
						openid: that.openid,
						phone: data.phoneNumber,
						type: 4
					}).then(res => {
						if (res.code == 0) {
							uni.setStorageSync('token', res.data.token);
							uni.setStorageSync('user', res.data.user);
							uni.setStorageSync('show', res.data.show);
							that.$u.toast('登录成功!正在跳转……');
							setTimeout(() => {
								if (that.bid.id && that.bid.name) {
									// 扫码进入
									uni.reLaunch({
										url: './certification?id=' + that.bid.id + '&name=' + that
											.bid.name
									})
								} else if (that.auditId) {
									// 企业微信通知进入-认证审核页面
									uni.reLaunch({
										url: './certificationAuditPersonalInfo?id=' +
											that.auditId
									})
								} else {
									uni.reLaunch({
										url: './certification'
									})
								}
							}, 1500);
						}
					})
				} else if (e.detail.errMsg === 'getPhoneNumber:fail user deny') {
					console.log('拒绝');
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.main {
		padding: 0 30rpx;
		height: 100vh;
		background: #fff;

		.tips {
			padding-top: 40vh;
			text-align: center;
		}

		.logo {
			border-bottom: 1rpx solid #D8D8D8;
			height: 30vh;
			text-align: center;
			line-height: 40vh;

			image {
				width: 160rpx;
				height: 160rpx;
			}
		}

		.h1 {
			color: #000000;
			margin-top: 40rpx;
			font-weight: 600;
			font-size: 32rpx;
		}

		.p {
			color: #999999;
			font-size: 32rpx;
			margin-top: 32rpx;
		}

		.btn-wrap {
			margin: 140rpx 0;

			.btn {
				font-size: 32rpx;
				font-family: PingFang SC;
				font-weight: 500;
				background-color: #30A1FF;
				color: #FFFFFF;
				border-radius: 40rpx;
				height: 80rpx;
				line-height: 80rpx;
			}

			.btn::after {
				border: none;
			}
		}
	}
</style>
